package com.wtwd.campus.receiver;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.constant.SignConstant;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.fjryE15.untils.XyyUtiils;
import com.wtwd.campus.h5_manager.entity.DeviceLog;
import com.wtwd.campus.h5_manager.service.DeviceLogService;
import com.wtwd.campus.service.*;
import com.wtwd.campus.utils.*;
import com.wtwd.campus.utils.Vizhi.VizhiService;
import com.wtwd.campus.utils.Vizhi.entity.Address;
import com.wtwd.campus.utils.Vizhi.entity.Point;
import com.wtwd.campus.utils.Vizhi.entity.Position;
import com.wtwd.campus.utils.Vizhi.entity.vo.VizhiVo;
import com.wtwd.campus.vcom.common.Constant;
import com.wtwd.campus.vcom.entity.VcomWarningRecord;
import com.wtwd.campus.vcom.service.VcomH5Service;
import com.wtwd.campus.vcom.utils.VcomPushUtils;
import com.wtwd.campus.wx.service.WxUtilsService;
import com.wtwd.campus.wx.utils.PushModel;
import com.wtwd.campus.wx.utils.WxUtils;
import org.apache.commons.lang.StringUtils;
import org.jeewx.api.core.req.model.message.TemplateMessageSendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;

@Service
@MsgType(value = Constants.SOS_WARNING)
public class SOSWarningReceiverHandler implements IReceiverHandler {

    @Value("${web.customerCode.xb}")
    private String xbCustomerCode;

    @Value("${web.customerCode.cw}")
    private String cwCustomerCode;

    @Value("${h5.customerId.ryh5}")
    private Integer ryh5CustomerId;

    @Value("${h5.customerId.hbDxRyh5}")
    private Integer hbDxRyh5CustomerId;

    @Value("${wx.general.push.customerCode}")
    private String wxPushCustomerCode;

    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private ReceiverUtils receiverUtils;
    @Autowired
    private WarningRecordService warningRecordService;
    @Autowired
    private IRMFeignClientService irmFeignClientService;
    @Autowired
    private PushUtils pushUtils;
    @Autowired
    private WxService wxService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private VcomPushUtils vcomPushUtils;
    @Autowired
    private VcomH5Service vcomH5Service;
    @Autowired
    private DeviceLogService deviceLogService;
    @Autowired
    private WxUtilsService wxUtilsService;

    @Resource
    private VizhiService vizhiService;

    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqSOSUpMessage mqSOSUpMessage = (MqSOSUpMessage) mqMessage.getObject();
        String imei = mqSOSUpMessage.getImei();
        String commandNumber = mqSOSUpMessage.getCommandNumber();
        //进行指令回复
        irmFeignClientService.replySOS(imei, commandNumber);
        //处理指令上报的时间
        String date = mqSOSUpMessage.getDeviceDate();
        String time1 = mqSOSUpMessage.getDeviceTime();
        Long time = getTime(date, time1);
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        String wifiInfo = mqSOSUpMessage.getWifiInfo();
        MqLocationData mqLocationData = mqSOSUpMessage.getMqLocationData();
        if (deviceInfo != null) {
            if (mqLocationData != null) {
                if (mqLocationData.getLatitude() != 0 && mqLocationData.getLongitude() != 0) {
                    //进行定位数据存储以及围栏告警记录的存储
                    deviceInfo = receiverUtils.dealLocation(mqLocationData, time, deviceInfo, 1);
                } else {
                    //当没有gps定位时，从wifi数据中拿到定位
//                    JSONObject wifiAddress = GaoDeUtil.getWifiAddress(wifiInfo, imei);
//                    JSONObject result = (JSONObject) wifiAddress.get("result");
//                    String location = (String) result.get("location");
                    VizhiVo wifiAddress = vizhiService.intelligentHardwareLocation(imei, wifiInfo,null);
                    if (wifiAddress==null){
                        return;
                    }
                    Address address = wifiAddress.getLocation().getAddress();
                    if (address!=null&& StringUtils.isNotBlank(address.getName())){
                        mqLocationData.setAddress(address.getName());
                    }
                    Position position = wifiAddress.getLocation().getPosition();
                    Point point = position.getPoint();
                    String[] split = {String.valueOf(point.getLongitude()),String.valueOf(point.getLatitude())};
                    double[] lgtLat = GPSUtils.gcj02_To_Gps84(Double.parseDouble(split[1]), Double.parseDouble(split[0]));
                    logger.info("SOS告警，转GPS坐标：[{}]", lgtLat);
                    mqLocationData.setLongitude(lgtLat[1]);
                    mqLocationData.setLatitude(lgtLat[0]);
                        //存储定位信息以及围栏告警
                    deviceInfo = receiverUtils.dealLocation(mqLocationData, time, deviceInfo, 2);
                }
            }
            //修改设备信息
            deviceInfo.setLastUpTime(System.currentTimeMillis());
            deviceInfoService.modifyDeviceInfo(deviceInfo);
            if (deviceInfo.getDeviceType() == Constants.VCOM_DEVICE) {
                //存储威科姆设备的SOS告警信息
                List<String> studentIds = vcomH5Service.getStudentIdByImei(deviceInfo.getImei());
                if (studentIds != null && studentIds.size() > 0) {
                    for (String studentId : studentIds) {
                        VcomWarningRecord record = new VcomWarningRecord();
                        record.setType(Constant.WARNING_SOS);
                        record.setTime(time);
                        Map<String, Object> message = new HashMap<>();
                        message.put("longitude", mqLocationData.getLongitude());
                        message.put("latitude", mqLocationData.getLatitude());
                        message.put("address", deviceInfo.getAddress());
                        record.setMessage(JSONObject.toJSONString(message));
                        record.setImei(deviceInfo.getImei());
                        record.setStudentId("0");
                        if (!StringUtils.isBlank(studentId)) {
                            record.setStudentId(studentId);
                        }
                        vcomH5Service.addVcomWarningRecord(record);
                    }
                } else {
                    VcomWarningRecord record = new VcomWarningRecord();
                    record.setType(Constant.WARNING_SOS);
                    record.setTime(time);
                    Map<String, Object> message = new HashMap<>();
                    message.put("longitude", mqLocationData.getLongitude());
                    message.put("latitude", mqLocationData.getLatitude());
                    message.put("address", deviceInfo.getAddress());
                    record.setMessage(JSONObject.toJSONString(message));
                    record.setImei(deviceInfo.getImei());
                    record.setStudentId("0");
                    vcomH5Service.addVcomWarningRecord(record);
                }
            } else {
                //存储平台的SOS告警信息
                WarningRecord record = new WarningRecord();
                record.setDevice_id(deviceInfo.getDeviceId());
                record.setWarning_type(Constants.SOS_WARNING_TYPE);
                record.setWarning_time(time);
                record.setAddress(deviceInfo.getAddress());
                warningRecordService.addWarningRecord(record);
            }
//            //进行指令回复
//            irmFeignClientService.replySOS(imei, commandNumber);
            // 推送处理
            if (deviceInfo.getCustomerId() != null) {
                pushUtils.pushSOSWarn(deviceInfo, mqLocationData);
            }
            // 和校园SOS推送
            if (deviceInfo.getDeviceType() == Constants.HXY_DEVICE) {
                Double longitude = mqLocationData.getLongitude();
                Double latitude = mqLocationData.getLatitude();
                double[] doubles = GPSUtils.gps84_To_Gcj02(latitude, longitude);
                // 转高德经纬度
                pushUtils.pushHxySos(imei, doubles[1], doubles[0], DateUtils.format(new Date(), DateUtils.dateFormat4));
            }
            //推送威科姆的sos告警信息
            if (deviceInfo.getDeviceType() == Constants.VCOM_DEVICE) {
                vcomPushUtils.pushWarning(mqLocationData.getLatitude(), mqLocationData.getLongitude(), deviceInfo.getAddress(), 1, "SOS告警:".concat(deviceInfo.getAddress()), System.currentTimeMillis(), imei, "", "");
            }
            //如果是H5设备
            if (deviceInfo.getDeviceType() == Constants.H5_DEVICE) {
                if (deviceInfo.getCustomerId() == 5 || deviceInfo.getCustomerId() == 8) {
                    pushUtils.hnh5PushAlarmInfo(deviceInfo.getImei(), "SOS上报", DateUtils.format(new Date(), DateUtils.dateFormat1), deviceInfo.getAddress(), null, null);
                } else if (ryh5CustomerId.equals(deviceInfo.getCustomerId())) {
                    SosReport sosReport = new SosReport();
                    sosReport.setImei(deviceInfo.getImei());
                    sosReport.setLng(String.valueOf(mqLocationData.getLongitude()));
                    sosReport.setLat(String.valueOf(mqLocationData.getLatitude()));
                    sosReport.setPosition(deviceInfo.getAddress());
                    sosReport.setReportTime(DateUtils.format(new Date(), DateUtils.dateFormat15));
                    XyyUtiils.pushSosReport(sosReport);
                } else if (hbDxRyh5CustomerId.equals(deviceInfo.getCustomerId())) {
                    HbDxE15RyPushEntity hbDxE15RyPushEntity = new HbDxE15RyPushEntity();
                    hbDxE15RyPushEntity.setImei(deviceInfo.getImei());
                    hbDxE15RyPushEntity.setmType(HbDxE15RyPushEntity.PushTypeEnum.ALARM_TYPE.getType());
                    hbDxE15RyPushEntity.setmClass(HbDxE15RyPushEntity.MessageType.SOS_MESSAGE.getType());
                    hbDxE15RyPushEntity.setmTime(DateUtils.format(new Date(), DateUtils.dateFormat4));
                    hbDxE15RyPushEntity.setMemo(MessageFormat.format(HbDxE15RyPushEntity.MessageType.SOS_MESSAGE.getTemplate(), deviceInfo.getImei(), deviceInfo.getAddress(), DateUtils.format(new Date(), DateUtils.dateFormat4)));
                    HbDxE15RyUtiils.hbDxE15RyPush(hbDxE15RyPushEntity);
                }
            }
            //如果是平台设备，推送到微信（不推瑞翼和喜马拉雅）
            if (!StringUtils.isBlank(deviceInfo.getOrgCode()) && !deviceInfo.getOrgCode().contains("A01A03A05") && !deviceInfo.getOrgCode().contains("A01A07") && !deviceInfo.getOrgCode().contains("A01A38")) {
                //根据学生id查询推送openID
                if (deviceInfo.getStudentId() != null) {
                    List<Map<String, Object>> openIdList = wxService.getOpenIdByStuId(deviceInfo.getStudentId());
                    //获取学生的基本信息
                    Map<String, Object> stuMess = studentService.getStuMessByStuId(deviceInfo.getStudentId());
                    JSONObject obj = new JSONObject();
                    obj.put("imei",imei);
                    obj.put("stuName", stuMess.get("student_name"));
                    obj.put("time", time);
                    obj.put("schoolName", stuMess.get("school_name"));
                    obj.put("className", stuMess.get("classes_name"));
                    obj.put("gradeName", stuMess.get("grade_name"));
                    obj.put("address", deviceInfo.getAddress());
                    if (deviceInfo.getOrgCode().startsWith(cwCustomerCode)) {
                        openIdList.stream().forEach(e -> {
                            TemplateMessageSendResult sosRecordTemplate = PushModel.createSosRecordTemplateCW(obj);
                            sosRecordTemplate.setUrl("");
                            String openId = (String) e.get("open_id");
                            if (!StringUtils.isBlank(openId)) {
                                sosRecordTemplate.setTouser(openId);
                                WxUtils.pushMsgCW(sosRecordTemplate);
                            }
                        });
                    } else if (deviceInfo.getOrgCode().startsWith(xbCustomerCode)) {
                        openIdList.stream().forEach(e -> {
                            TemplateMessageSendResult sosRecordTemplate = PushModel.createSosRecordTemplateXB(obj);
                            sosRecordTemplate.setUrl("");
                            String openId = (String) e.get("open_id");
                            if (!StringUtils.isBlank(openId)) {
                                sosRecordTemplate.setTouser(openId);
                                WxUtils.pushMsgXB(sosRecordTemplate);
                            }
                        });
                    } else {
                        String pushCode = "";
                        if (StringUtils.isNotBlank(wxPushCustomerCode)&&StringUtils.isNotBlank(deviceInfo.getOrgCode())){
                            List<String> customerCodeString = Arrays.asList(wxPushCustomerCode.split(SignConstant.COMMA));
                             pushCode = wxUtilsService.getWxCustomerCode(customerCodeString, deviceInfo.getOrgCode());
                            if (StringUtils.isNotBlank(pushCode)){
                                TemplateMessageSendResult sosRecordTemplate = wxUtilsService.createSosRecordTemplate(pushCode, obj);
                                sosRecordTemplate.setUrl("");
                                for (Map<String, Object> e : openIdList) {
                                    String openId = (String) e.get("open_id");
                                    if (!StringUtils.isBlank(openId)) {
                                        sosRecordTemplate.setTouser(openId);
                                        wxUtilsService.pushMsg(pushCode,sosRecordTemplate);
                                    }
                                }
                            }
                        }if (StringUtils.isBlank(pushCode)){
                            openIdList.stream().forEach(e -> {
                                TemplateMessageSendResult sosRecordTemplate = PushModel.createSosRecordTemplate(obj);
                                sosRecordTemplate.setUrl("");
                                String openId = (String) e.get("open_id");
                                if (!StringUtils.isBlank(openId)) {
                                    sosRecordTemplate.setTouser(openId);
                                    WxUtils.pushMsg(sosRecordTemplate);
                                }
                            });
                        }
                    }
                }
            }
            //存储设备接收日志
            DeviceLog deviceLog = new DeviceLog();
            deviceLog.setSendUser(Constants.DEVICE_USER);
            deviceLog.setImei(imei);
            deviceLog.setBigType(Constants.MESS_TYPE);
            JSONObject contant = new JSONObject();
            contant.put("设备号", imei);
            contant.put("Wifi信息", mqSOSUpMessage.getWifiInfo());
            contant.put("日月年", date);
            contant.put("经度", mqSOSUpMessage.getMqLocationData().getLongitude());
            contant.put("纬度", mqSOSUpMessage.getMqLocationData().getLatitude());
            contant.put("速度", mqSOSUpMessage.getMqLocationData().getSpeed());
            contant.put("方位角", mqSOSUpMessage.getMqLocationData().getOrientation());
            contant.put("设备状态", mqSOSUpMessage.getDeviceStatus());
            deviceLog.setCmd(contant.toJSONString());
            deviceLog.setSendTime(System.currentTimeMillis());
            deviceLog.setCommandNumber(commandNumber);
            deviceLog.setState(1);
            deviceLogService.addDeviceLog(deviceLog);
        } else {
            saveUnInStorage(imei);
            receiverUtils.cloaseChannel(imei);
        }
    }
}
